package ll.sms.db;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbutils.DbUtils;

import ll.sms.exceptions.SmsDBException;
import ll.sms.factory.ConnectionFactory;
import ll.sms.factory.Parameters;

public class Transaction {
	private static final ThreadLocal<Connection> threadConn = new ThreadLocal<Connection>();

	public static void begin() {
		try {
			SmsDataSource.initDataSource();
			Connection conn = ConnectionFactory.getConnection(Parameters.Connection.C3P0);
			conn.setAutoCommit(false);
			threadConn.set(conn);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new SmsDBException(e);
		}
	}

	public static void commit() {
		Connection conn=null;
		try {
			conn = threadConn.get();
			conn.commit();
			conn.setAutoCommit(true);
			threadConn.remove();
			threadConn.set(null);
			DbUtils.closeQuietly(conn);
		} catch (Exception e) {
			e.printStackTrace();
			rollBack();
			throw new SmsDBException(e);
		}
	}

	public static void rollBack() {
		Connection conn = threadConn.get();
		try {
			conn.rollback();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			threadConn.remove();
			threadConn.set(null);
			DbUtils.closeQuietly(conn);
		}
	}

	public static Connection currentConnection() {
		return threadConn.get();
	}
}
